package control;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import model.Element;
import model.Player;
import model.World;
import model.element.Building;
import model.element.ElementFactory;
import model.element.Road;
import utility.Maths;
import view.Map;

public class MapMouseListener implements MouseListener, MouseMotionListener{
	
	private Player player;
	private Game game;
	private Map map;
	private Element selected = null;
	private World world;
	
	public MapMouseListener(Player player, Game game, Map map, World world){
		this.player = player;
		this.game = game;
		this.map = map;
		this.world = world;
	}
	
	public void select(Element e){
		this.selected = e;
	}
	public void build(MouseEvent m){
		if(player.allow(selected)){
			ElementFactory factory = new ElementFactory();
			Rectangle rect = new Rectangle(Maths.truncate(m.getX()+map.getDX(), Road.ROAD_SIZE), Maths.truncate(m.getY()+map.getDY(), Road.ROAD_SIZE), selected.getWidth(), selected.getHeight());
			selected.setRectangle(rect);
			if(!world.blocked(selected)){
				if(selected instanceof Road){
					game.addElement(factory.createRoad(rect, world));
				}else if(selected instanceof Building){
					game.addElement(new Building(rect));
				}
			}
		}
	}
	
	public void mouseClicked(MouseEvent m) {
	}
	public void mouseEntered(MouseEvent arg0) {	}
	public void mouseExited(MouseEvent arg0) {
	}
	public void mousePressed(MouseEvent m) {
		build(m);
	}
	public void mouseReleased(MouseEvent arg0) {
	}
	public void mouseDragged(MouseEvent m) {
		build(m);
	}
	public void mouseMoved(MouseEvent m) {
//		map.updateUI();
//		Graphics g = map.getGraphics();
//		g.setColor(Color.BLACK);
//		g.drawRect(m.getX(), m.getY(), 50, 50);
	}
}
